package com.zouxw.utils.json.view;

import com.zouxw.utils.json.utils.JsonSchemaValidator;
import com.zouxw.utils.json.utils.SchemaManager;

import javax.swing.*;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.List;

/**
 * Schema验证对话框
 * 提供Schema验证的用户界面
 * 
 * @author zouxw
 * @version 1.0.0
 */
public class SchemaValidationDialog extends JDialog {
    
    private JTextArea jsonTextArea;
    private JTextArea schemaTextArea;
    private JTextArea resultTextArea;
    private JComboBox<String> schemaComboBox;
    private JButton validateButton;
    private JButton loadSchemaButton;
    private JButton saveSchemaButton;
    private JButton generateSchemaButton;
    private JButton clearButton;
    private JLabel statusLabel;
    
    private SchemaManager schemaManager;
    private JsonSchemaValidator.ValidationResult lastResult;
    
    /**
     * 构造函数
     * 
     * @param parent 父组件
     * @param jsonContent 初始JSON内容
     */
    public SchemaValidationDialog(Component parent, String jsonContent) {
        super((Frame) SwingUtilities.getWindowAncestor(parent), "JSON Schema验证", true);
        
        this.schemaManager = new SchemaManager();
        this.lastResult = null;
        
        initializeComponents();
        setupLayout();
        setupEventHandlers();
        loadSavedSchemas();
        
        if (jsonContent != null && !jsonContent.trim().isEmpty()) {
            jsonTextArea.setText(jsonContent);
        }
        
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        setSize(1000, 700);
        setLocationRelativeTo(parent);
    }
    
    /**
     * 初始化组件
     */
    private void initializeComponents() {
        // JSON输入区域
        jsonTextArea = new JTextArea(10, 40);
        jsonTextArea.setFont(new Font("Consolas", Font.PLAIN, 12));
        jsonTextArea.setBorder(new TitledBorder("JSON数据"));
        jsonTextArea.setLineWrap(true);
        jsonTextArea.setWrapStyleWord(true);
        
        // Schema输入区域
        schemaTextArea = new JTextArea(10, 40);
        schemaTextArea.setFont(new Font("Consolas", Font.PLAIN, 12));
        schemaTextArea.setBorder(new TitledBorder("JSON Schema"));
        schemaTextArea.setLineWrap(true);
        schemaTextArea.setWrapStyleWord(true);
        
        // 结果显示区域
        resultTextArea = new JTextArea(8, 40);
        resultTextArea.setFont(new Font("Consolas", Font.PLAIN, 12));
        resultTextArea.setBorder(new TitledBorder("验证结果"));
        resultTextArea.setEditable(false);
        resultTextArea.setBackground(Color.WHITE);
        
        // Schema选择下拉框
        schemaComboBox = new JComboBox<>();
        schemaComboBox.setBorder(new TitledBorder("已保存的Schema"));
        schemaComboBox.addActionListener(e -> loadSelectedSchema());
        
        // 按钮
        validateButton = new JButton("验证 (Ctrl+Enter)");
        loadSchemaButton = new JButton("加载Schema");
        saveSchemaButton = new JButton("保存Schema");
        generateSchemaButton = new JButton("生成Schema");
        clearButton = new JButton("清空");
        
        // 状态标签
        statusLabel = new JLabel("就绪");
        statusLabel.setBorder(BorderFactory.createLoweredBevelBorder());
    }
    
    /**
     * 设置布局
     */
    private void setupLayout() {
        setLayout(new BorderLayout());
        
        // 顶部面板 - Schema选择
        JPanel topPanel = new JPanel(new BorderLayout());
        topPanel.add(schemaComboBox, BorderLayout.CENTER);
        topPanel.add(loadSchemaButton, BorderLayout.EAST);
        topPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        
        // 中间面板 - 输入区域
        JPanel inputPanel = new JPanel(new GridLayout(1, 2, 10, 0));
        
        // JSON输入面板
        JPanel jsonPanel = new JPanel(new BorderLayout());
        jsonPanel.add(new JScrollPane(jsonTextArea), BorderLayout.CENTER);
        jsonPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        
        // Schema输入面板
        JPanel schemaPanel = new JPanel(new BorderLayout());
        schemaPanel.add(new JScrollPane(schemaTextArea), BorderLayout.CENTER);
        schemaPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        
        inputPanel.add(jsonPanel);
        inputPanel.add(schemaPanel);
        
        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout());
        buttonPanel.add(validateButton);
        buttonPanel.add(Box.createHorizontalStrut(10));
        buttonPanel.add(saveSchemaButton);
        buttonPanel.add(Box.createHorizontalStrut(10));
        buttonPanel.add(generateSchemaButton);
        buttonPanel.add(Box.createHorizontalStrut(10));
        buttonPanel.add(clearButton);
        
        // 结果面板
        JPanel resultPanel = new JPanel(new BorderLayout());
        resultPanel.add(new JScrollPane(resultTextArea), BorderLayout.CENTER);
        resultPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        
        // 底部面板 - 状态栏
        JPanel bottomPanel = new JPanel(new BorderLayout());
        bottomPanel.add(statusLabel, BorderLayout.CENTER);
        bottomPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        
        // 主面板
        JPanel mainPanel = new JPanel(new BorderLayout());
        mainPanel.add(inputPanel, BorderLayout.CENTER);
        mainPanel.add(buttonPanel, BorderLayout.SOUTH);
        
        // 添加所有面板
        add(topPanel, BorderLayout.NORTH);
        add(mainPanel, BorderLayout.CENTER);
        add(resultPanel, BorderLayout.SOUTH);
        add(bottomPanel, BorderLayout.PAGE_END);
    }
    
    /**
     * 设置事件处理器
     */
    private void setupEventHandlers() {
        // 验证按钮
        validateButton.addActionListener(e -> performValidation());
        
        // 加载Schema按钮
        loadSchemaButton.addActionListener(e -> loadSchemaFromFile());
        
        // 保存Schema按钮
        saveSchemaButton.addActionListener(e -> saveCurrentSchema());
        
        // 生成Schema按钮
        generateSchemaButton.addActionListener(e -> generateSchemaFromJson());
        
        // 清空按钮
        clearButton.addActionListener(e -> clearAll());
        
        // 键盘快捷键
        setupKeyboardShortcuts();
    }
    
    /**
     * 设置键盘快捷键
     */
    private void setupKeyboardShortcuts() {
        // 验证快捷键
        getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
            .put(KeyStroke.getKeyStroke("ctrl ENTER"), "validate");
        getRootPane().getActionMap().put("validate", new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                performValidation();
            }
        });
    }
    
    /**
     * 执行验证
     */
    private void performValidation() {
        String jsonContent = jsonTextArea.getText().trim();
        String schemaContent = schemaTextArea.getText().trim();
        
        if (jsonContent.isEmpty()) {
            showError("请输入JSON数据");
            return;
        }
        
        if (schemaContent.isEmpty()) {
            showError("请输入JSON Schema");
            return;
        }
        
        try {
            statusLabel.setText("正在验证...");
            validateButton.setEnabled(false);
            
            // 执行验证
            lastResult = JsonSchemaValidator.validate(jsonContent, schemaContent);
            
            // 显示结果
            displayValidationResult(lastResult);
            
            // 更新状态
            if (lastResult.isValid()) {
                statusLabel.setText("验证通过");
                statusLabel.setForeground(Color.GREEN);
            } else {
                statusLabel.setText("验证失败");
                statusLabel.setForeground(Color.RED);
            }
            
        } catch (Exception e) {
            showError("验证过程中发生错误: " + e.getMessage());
            statusLabel.setText("验证错误");
            statusLabel.setForeground(Color.RED);
        } finally {
            validateButton.setEnabled(true);
        }
    }
    
    /**
     * 显示验证结果
     * 
     * @param result 验证结果
     */
    private void displayValidationResult(JsonSchemaValidator.ValidationResult result) {
        StringBuilder sb = new StringBuilder();
        
        // 验证状态
        sb.append("验证状态: ").append(result.isValid() ? "✅ 通过" : "❌ 失败").append("\n");
        sb.append("摘要: ").append(result.getSummary()).append("\n\n");
        
        // 错误信息
        if (result.hasErrors()) {
            sb.append("错误信息:\n");
            for (String error : result.getErrors()) {
                sb.append("  ❌ ").append(error).append("\n");
            }
            sb.append("\n");
        }
        
        // 警告信息
        if (result.hasWarnings()) {
            sb.append("警告信息:\n");
            for (String warning : result.getWarnings()) {
                sb.append("  ⚠️ ").append(warning).append("\n");
            }
            sb.append("\n");
        }
        
        // 验证时间
        sb.append("验证时间: ").append(new java.util.Date().toString());
        
        resultTextArea.setText(sb.toString());
        resultTextArea.setCaretPosition(0);
    }
    
    /**
     * 加载选中的Schema
     */
    private void loadSelectedSchema() {
        String selectedSchema = (String) schemaComboBox.getSelectedItem();
        if (selectedSchema != null && !selectedSchema.isEmpty()) {
            String content = schemaManager.loadSchema(selectedSchema);
            if (content != null) {
                schemaTextArea.setText(content);
                statusLabel.setText("已加载Schema: " + selectedSchema);
            }
        }
    }
    
    /**
     * 从文件加载Schema
     */
    private void loadSchemaFromFile() {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
            @Override
            public boolean accept(File f) {
                return f.isDirectory() || f.getName().toLowerCase().endsWith(".json");
            }
            
            @Override
            public String getDescription() {
                return "JSON文件 (*.json)";
            }
        });
        
        if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
            try {
                File selectedFile = fileChooser.getSelectedFile();
                byte[] bytes = Files.readAllBytes(selectedFile.toPath());
                String content = new String(bytes, StandardCharsets.UTF_8);
                schemaTextArea.setText(content);
                statusLabel.setText("已加载Schema文件: " + selectedFile.getName());
            } catch (Exception e) {
                showError("加载Schema文件失败: " + e.getMessage());
            }
        }
    }
    
    /**
     * 保存当前Schema
     */
    private void saveCurrentSchema() {
        String schemaContent = schemaTextArea.getText().trim();
        if (schemaContent.isEmpty()) {
            showError("Schema内容为空");
            return;
        }
        
        // 验证Schema格式
        if (!JsonSchemaValidator.isValidSchema(schemaContent)) {
            showError("Schema格式无效");
            return;
        }
        
        // 获取Schema名称和描述
        String name = JOptionPane.showInputDialog(this, "请输入Schema名称:", "保存Schema", JOptionPane.QUESTION_MESSAGE);
        if (name == null || name.trim().isEmpty()) {
            return;
        }
        
        String description = JOptionPane.showInputDialog(this, "请输入Schema描述:", "保存Schema", JOptionPane.QUESTION_MESSAGE);
        if (description == null) {
            description = "";
        }
        
        // 保存Schema
        if (schemaManager.saveSchema(name.trim(), description.trim(), schemaContent, "用户")) {
            showInfo("Schema保存成功: " + name);
            loadSavedSchemas();
            schemaComboBox.setSelectedItem(name);
        } else {
            showError("Schema保存失败");
        }
    }
    
    /**
     * 从JSON生成Schema
     */
    private void generateSchemaFromJson() {
        String jsonContent = jsonTextArea.getText().trim();
        if (jsonContent.isEmpty()) {
            showError("请先输入JSON数据");
            return;
        }
        
        try {
            String generatedSchema = JsonSchemaValidator.generateSchema(jsonContent);
            schemaTextArea.setText(generatedSchema);
            statusLabel.setText("已生成Schema");
        } catch (Exception e) {
            showError("生成Schema失败: " + e.getMessage());
        }
    }
    
    /**
     * 清空所有内容
     */
    private void clearAll() {
        int result = JOptionPane.showConfirmDialog(this, 
            "确定要清空所有内容吗？", "确认清空", 
            JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
        
        if (result == JOptionPane.YES_OPTION) {
            jsonTextArea.setText("");
            schemaTextArea.setText("");
            resultTextArea.setText("");
            statusLabel.setText("已清空");
        }
    }
    
    /**
     * 加载已保存的Schema
     */
    private void loadSavedSchemas() {
        schemaComboBox.removeAllItems();
        schemaComboBox.addItem(""); // 空选项
        
        List<String> schemaNames = schemaManager.getAllSchemaNames();
        for (String name : schemaNames) {
            schemaComboBox.addItem(name);
        }
    }
    
    /**
     * 显示错误信息
     * 
     * @param message 错误信息
     */
    private void showError(String message) {
        JOptionPane.showMessageDialog(this, message, "错误", JOptionPane.ERROR_MESSAGE);
    }
    
    /**
     * 显示信息
     * 
     * @param message 信息
     */
    private void showInfo(String message) {
        JOptionPane.showMessageDialog(this, message, "信息", JOptionPane.INFORMATION_MESSAGE);
    }
    
    /**
     * 获取最后的验证结果
     * 
     * @return 验证结果
     */
    public JsonSchemaValidator.ValidationResult getLastResult() {
        return lastResult;
    }
    
    /**
     * 设置JSON内容
     * 
     * @param jsonContent JSON内容
     */
    public void setJsonContent(String jsonContent) {
        jsonTextArea.setText(jsonContent);
    }
    
    /**
     * 设置Schema内容
     * 
     * @param schemaContent Schema内容
     */
    public void setSchemaContent(String schemaContent) {
        schemaTextArea.setText(schemaContent);
    }
}
